package cn.jlearn.proxy.server.listener;

import cn.jlearn.proxy.common.body.TcpTunnelBody;
import cn.jlearn.proxy.common.enums.MsgTypeEnum;
import cn.jlearn.proxy.common.enums.ProtocolEnum;
import cn.jlearn.proxy.common.packet.BsPacket;
import cn.jlearn.proxy.common.utils.PropertiesUtil;
import cn.jlearn.proxy.server.container.ProxyServer;
import cn.jlearn.proxy.server.utils.RedissonUtil;
import com.alibaba.fastjson.JSON;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioListener;


/**
 * @author qianyingchao
 * @version 1.0
 * @date 2021/5/10 6:13 下午
 */
public class TcpForwardServerListener implements ServerAioListener {

    @Override
    public boolean onHeartbeatTimeout(ChannelContext channelContext, Long interval, int heartbeatTimeoutCount) {
        return false;
    }

    @Override
    public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception {
        if (isConnected) {
            String bsId = channelContext.getId();
            Tio.bindBsId(channelContext, bsId);

            BsPacket bsPacket = new BsPacket(MsgTypeEnum.TCP_TUNNEL_OPEN_REQ.getCode(),
                    JSON.toJSONBytes(new TcpTunnelBody(bsId, ProtocolEnum.TCP.getCode())));

            String host =
                    PropertiesUtil.getProperty("tcp.forward.domain") + ":" + channelContext.getServerNode().getPort();
            String token = RedissonUtil.getInstance().get(host);
            channelContext.set("token", token);
            Tio.sendToBsId(ProxyServer.serverTioConfig, token, bsPacket);
        }
    }

    @Override
    public void onAfterDecoded(ChannelContext channelContext, Packet packet, int packetSize) throws Exception {
    }

    @Override
    public void onAfterReceivedBytes(ChannelContext channelContext, int receivedBytes) throws Exception {
    }

    @Override
    public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) throws Exception {
    }

    @Override
    public void onAfterHandled(ChannelContext channelContext, Packet packet, long cost) throws Exception {
    }

    @Override
    public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception {
        String bsId = channelContext.getId();

        BsPacket bsPacket = new BsPacket(MsgTypeEnum.TCP_TUNNEL_CLOSE_REQ.getCode(),
                JSON.toJSONBytes(new TcpTunnelBody(bsId, ProtocolEnum.TCP.getCode())));

        String token = (String) channelContext.get("token");
        Tio.sendToBsId(ProxyServer.serverTioConfig, token, bsPacket);
    }

}
